﻿using Microsoft.AspNetCore.OData.Extensions;
using Microsoft.OData.Edm;
using Microsoft.OData.UriParser;

namespace EasyXaf.Sample.ODataService;

public static class HttpRequestExtensions
{
    public static bool TryParseRelatedKey(this HttpRequest request, Uri link, out string relatedKey)
    {
        relatedKey = null;
        var serviceRoot = request.CreateODataLink();
        var model = request.GetRouteServices().GetService(typeof(IEdmModel)) as IEdmModel;
        var uriParser = new ODataUriParser(model, new Uri(serviceRoot), link);
        var odataPath = uriParser.ParsePath();
        var keySegment = odataPath.OfType<KeySegment>().LastOrDefault();
        if (keySegment == null)
        {
            return false;
        }
        relatedKey = keySegment.Keys.First().Value.ToString();
        return true;
    }
}
